package org.peterbjornx.io;

import org.peterbjornx.cypher.ISAACRandom;

import java.io.DataInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by IntelliJ IDEA.
 * User: PeterbjornX
 * Date: Apr 7, 2009
 * Time: 7:39:50 PM
 * Extends the functionality of the DataInputStream
 * 
 */
public class RSInputStream extends DataInputStream {
    private int len;

    /**
     * Creates a RSInputStream from a InputStream instance
     * @param in the inputstream
     * @param l the length
     */
    public RSInputStream ( InputStream in, int l ){
        super(in);
        len = l;
    }

    @SuppressWarnings({"ResultOfMethodCallIgnored"})
    public BitStream readBitBlock(int length) throws IOException {
        byte[] d = new byte[length];
        read(d);
        return new BitStream(d);
    }

    private ISAACRandom isaac;

    public int readISAACByte() throws IOException {
        return read() - isaac.val() & 0xff;
    }

    public void initISAACCypher(int[] seed){
        isaac = new ISAACRandom(seed);
    }
    public void set(InputStream byteout) {
       in = byteout;
    }
    public int readSignedWord() throws IOException {
        int i = readShort();
        if(i > 32767)
            i -= 0x10000;
        return i;
    }
    public short readUShort() throws IOException{
        return (short)(readShort()&0xFFFF);
    }
    public String readString10T() throws IOException {
        byte b[] = new byte[800];
        int p = 0;
        while ( true )
        {
            byte c = (byte) read();
            if (c == 10)
                break;
            b[p++] = c;
        }
        return new String(b,0,p);
    }

    public String readStringNT() throws IOException {
        String s = "";
        while ( true )
        {
            int c = read();
            if (c == 0)
                break;
            s += c;
        }
        return s;
    }

    public int read3Bytes() throws IOException {
        return ((read() & 0xff) << 16) + ((read() & 0xff) << 8) + (read() & 0xff);
    }

    public int size() {
        return len;
    }

    public int readShortA() throws IOException {
        return ((read() & 0xff) << 8) + (read() - 128 & 0xff);
    }

    public int readUByte() throws IOException {
        return read() & 0xFF;
    }
    public int readUnsignedWordBigEndianA() throws IOException {
		return (read() - 128 & 0xff)+ ((read() & 0xff) << 8);
	}
}
